package com.houzehui.cart.controller;

import com.alibaba.fastjson.JSON;
import com.houzehui.cart.config.JwtUtils;
import com.houzehui.cart.config.MsgResult;
import com.houzehui.cart.config.WebUtils;
import com.houzehui.cart.dto.CartDto;
import com.houzehui.cart.service.CartService;
import com.houzehui.cart.vo.CartVo;
import com.houzehui.cart.vo.ProductVo;
import com.houzehui.common.vo.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Set;
@Slf4j
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    CartService cartService;

    @Resource
    RedisTemplate redisTemplate;


    @PostMapping("addcart")
    public MsgResult addcart(@RequestBody CartDto cartDto){

        //获取当前登录用户
        String userInfo = jwtUtils.getUserInfo();
        LoginUserInfo loginUserInfo = JSON.parseObject(userInfo, LoginUserInfo.class);

        //添加购物车
        cartService.add(loginUserInfo.getId(),cartDto.getSkuId(),cartDto.getNumber());

        return MsgResult.succeed();

    }

    /**
     * 购物车查询列表接口
     *
     * @return
     */

    @Autowired
    JwtUtils jwtUtils;

    @GetMapping("getMyCart")
    public MsgResult getMyCart(){


        //获取当前登录用户
        String userInfo = jwtUtils.getUserInfo();
        LoginUserInfo loginUserInfo = JSON.parseObject(userInfo, LoginUserInfo.class);
        //判断购物车为空
        Boolean lock = redisTemplate.hasKey("myCart:" + loginUserInfo.getId());

        if(!lock){
            return MsgResult.fail("购物车暂时没有商品");
        }
        CartVo cartVo = cartService.myCart(loginUserInfo.getId());

        return MsgResult.succeed(cartVo);
    }


    @PostMapping("delectCartid")
    public MsgResult delectCartid(@RequestBody CartDto cartDto){
        //获取当前登录用户
        String userInfo = jwtUtils.getUserInfo();
        LoginUserInfo loginUserInfo = JSON.parseObject(userInfo, LoginUserInfo.class);
        //删除购物车商品
       cartService.delete(loginUserInfo.getId(),cartDto.getSkuId());

        return MsgResult.succeed();
    }
}
